var zTree;
var setting;
var tNode;
var imgBase64;
var parentNode;
$(document).ready(function(){
    setting = {
        view: {
            dblClickExpand: false,
            showLine: true,
            selectedMulti: false,
            addHoverDom: addHoverDom,//显示操作图标
            removeHoverDom: removeHoverDom,//移除图标
            selectedMulti: false,
            nameIsHTML: true //允许name支持html
        },
        data: {
            simpleData: {
                enable:true,
                idKey: "id",
                pIdKey: "pid",
                rootPId: ""
            }
        },
        callback: {
            beforeClick: function(treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj("tree");
                if (treeNode.isParent) {
                    zTree.expandNode(treeNode);
                    return false;
                } else {
                    return true;
                }
            },
            onRemove: zTreeOnRemove,//删除后
            onClick: zTreeOnClickRight,
            beforeRemove: zTreeBeforeRemove, //删除方法
            beforeDrag: beforeDrag, //用于捕获节点被拖拽之前的事件回调函数，并且根据返回值确定是否允许开启拖拽操作
            beforeDrop:beforeDrop, //用于捕获节点拖拽操作结束之前的事件回调函数，并且根据返回值确定是否允许此拖拽操作
            onDrop: onDrop
        },
        edit: {
            drag: {
                autoExpandTrigger: true
            },
            enable: true,
            showRenameBtn: false,
            showRemoveBtn: true,
            removeTitle: "删除"
             }
    };

    initTree();
});
//初始化树
function initTree() {
    $.ajax({
        url: host + "/tel/telBookOrgan/tree/0",
        async: false,
        type: "get",
        success: function (data) {
            var zNodes = data;
            var t = $("#tree");
            t = $.fn.zTree.init(t, setting, zNodes);
            zTree = $.fn.zTree.getZTreeObj("tree");
            fuzzySearch('#tree-search',null,true); //初始化模糊搜索方法
        }
    });
}
//新增节点
function addHoverDom(treeId, treeNode) {
    $("#addReset").click();

    if (treeNode.isParent) {
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
            + "' title='增加' onfocus='this.blur();'></span>";
        sObj.after(addStr);
    }
    var btn = $("#addBtn_" + treeNode.tId);
    if (btn) btn.bind("click", function () {
        $.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, {
            _title: function(title) {
                var $title = this.options.title || '&nbsp;'
                if( ("title_html" in this.options) && this.options.title_html == true )
                    title.html($title);
                else title.text($title);
            },
            options: {
                appendTo: "body",
                autoOpen: true,
                buttons: [],
                closeOnEscape: true,
                closeText: "Close",
                draggable: true,
                height: "auto",
                minHeight: 150,
                minWidth: 150,
                modal: false,
                position: {
                    my: "center",
                    at: "center",
                    of: window,
                    collision: "fit",
                    // Ensure the titlebar is always visible
                    using: function( pos ) {
                        var topOffset = $( this ).css( pos ).offset().top;
                        if ( topOffset < 0 ) {
                            $( this ).css( "top", pos.top - topOffset );
                        }
                    }
                },
                resizable: true,
                width: 550
            },

        }));

        var dialog = $( "#dialog-message" ).removeClass('hide').dialog({
            modal: true,
            title: "<div class='widget-header widget-header-small'><h4 class='smaller'><i class='ace-icon fa fa-floppy-o'></i> 添加</h4></div>",
            title_html: true,
            buttons: [
                {
                    text: "返回",
                    "class" : "btn btn-minier",
                    click: function() {
                        $("#addReset").click();
                        $( this ).dialog( "close" );
                    }
                },
                {
                    text: "增加",
                    "class" : "btn btn-primary btn-minier",
                    click: function() {
                        $("#parentId").val(treeNode.id);
                        addTreeNode(treeNode);
                        $( this ).dialog( "close" );
                    }
                }
            ]
        });


        return false;
    });
    return false;
};
//增加节点
function addTreeNode(treeNode) {
    var addData = $('#addForm').serializeObject();
    addData.organName = treeNode.name;
    addData.organId = treeNode.id;
        $.ajax({
        url: host + "/tel/telBookOrgan",
        data: addData,
        async: false,
        type: "post",
        success: function (data) {
            if (data.success == true) {
                var zTree = $.fn.zTree.getZTreeObj("tree");
                if($("#isOrgan").val()=="true"){
                    zTree.addNodes(treeNode, { id: data.msg, pid: treeNode.id, name:$(".iname").val(),isParent:true });
                }else{
                    zTree.addNodes(treeNode, { id: data.msg, pid: treeNode.id, name:$(".iname").val() });
                }
                $("#addReset").click();
            }
            else {

            }
        },
        error: function (e,ee,eee) {
            alert("新增失败");
        }
    });
}
//删除后
function zTreeOnRemove(event, treeId, treeNode) {


}
//删除节点
function zTreeBeforeRemove(event, treeId, treeNode) {
    $.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, {
        _title: function(title) {
            var $title = this.options.title || '&nbsp;'
            if( ("title_html" in this.options) && this.options.title_html == true )
                title.html($title);
            else title.text($title);
        }
    }));

    if(!treeId.isParent || !treeId.children){
        $( "#dialog-confirm" ).removeClass('hide').dialog({
            resizable: false,
            width: '320',
            modal: true,
            title: "<div class='widget-header'><h4 class='smaller'><i class='ace-icon fa fa-exclamation-triangle red'></i> 确认删除?</h4></div>",
            title_html: true,
            buttons: [
                {
                    html: "<i class='ace-icon fa fa-trash-o bigger-110'></i>&nbsp; 删除",
                    "class" : "btn btn-danger btn-minier",
                    click: function() {
                        //删除选中的节点
                        var id = treeId.id;
                        $.ajax({
                            url: host + "/tel/telBookOrgan/" + id,
                            async: false,
                            type: "delete",
                            success: function (data) {
                                if(data.success == true){
                                    zTree.removeNode(treeId);
                                }else {
                                    $.gritter.add({
                                        title: '错误!',
                                        text: '删除失败,请联系管理员',
                                        class_name: 'gritter-info gritter-center gritter-item gritter-error'
                                    });
                                }

                            }
                        });
                        $( this ).dialog( "close" );
                    }
                }
                ,
                {
                    html: "<i class='ace-icon fa fa-times bigger-110'></i>&nbsp; 关闭",
                    "class" : "btn btn-minier",
                    click: function(re) {
                        $( this ).dialog( "close" );
                    }
                }
            ]
        });
    } else {
        $.gritter.add({
            title: '含有成员的部门无法删除!',
            text: '请首先删除部门下所有成员再试,或者联系管理员',
            class_name: 'gritter-info gritter-center gritter-item gritter-error'
        });

        return false;
    }

    return false;
}

function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.tId).unbind().remove();

};
// 树的单击事件
function zTreeOnClickRight(event, treeId, treeNode) {
    tNode = treeNode;
    if(! treeNode.isParent ){
        var id = treeNode.id;
        $.ajax({
            url: host + "/tel/telBookOrgan/" + id,
            async: false,
            type: "get",
            success: function (data) {
                if(data.code == 200){
                    $("#top-content").hide();
                    $("#left-page").show();
                    var data = data.data;
                    var base64 = $.ajax({url:host + "/tel/telBookOrgan/img/" + id,type:"get",async:false});
                    imgBase64 = base64.responseText;
                    if(imgBase64 == null || imgBase64 == undefined || imgBase64 == ''){
                        imgBase64 = "assets/avatars/profile-pic.jpg";
                    }
                    data.imgFile = imgBase64;
                    var html = template('innerHtm', data);
                    document.getElementById('contents').innerHTML = html;
                    initImg();
                    formSet();
                    $("#home-content").click();
                    //修改
                    $("#updSubmit").click(function(){
                        update();
                    });
                }
            }
        });

    }
}
//判断该节点能否被拖拽
function beforeDrag(treeId, treeNodes) {
    if (treeNodes[0].isParent == true) {
        return false;
    } else {
        return true;
    }
    return false;
}
//节点拖拽操作结束之前的事件回调函数
function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
    parentNode = treeNodes[0].getParentNode();
    if(parentNode.id == targetNode.id){
        return false;
    }
    var flag = false;
    if(targetNode.isParent == false){
        return flag;
    } else {
      var data = {id:treeNodes[0].id,parentId:targetNode.id,organId:targetNode.id,organName:targetNode.name};
        $.ajax({
            url: host + "/tel/telBookOrgan",
            data: data,
            async: false,
            type: "put",
            success: function (data) {
                if (data.success == true) {
                    flag = true;
                }
                else {
                    flag = false;
                }
            }
        });
    }
    return flag;
}
function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
    if(parentNode.isParent == false){
        parentNode.isParent=true;
        zTree.updateNode(parentNode);  // 调用updateNode修改属性，一定要加这一句，不然reAsyncChildNodes没有任何反应
        zTree.reAsyncChildNodes(parentNode, 'refresh', false);
    }
}


//设置表单禁用和取消
function formSet() {
    $('#edit-form').find('input,textarea,button').attr('disabled',true);
    $('[data-rel=popover]').popover({container:'body'});

    $('#disable-check').on('click', function() {
        var inp = $('#edit-form #name').get(0);
        if(inp.hasAttribute('disabled')) {
            $('#help-span').attr("data-content","点击锁定表单");
            $('#edit-form').find('input,textarea,button').attr('disabled',false);
        }
        else {
            $('#help-span').attr("data-content","点击解锁表单");
            $('#edit-form').find('input,textarea,button').attr('disabled',true);
        }
    });
}

/**
 *
 * @param searchField 输入框选择器
 * @param isHighLight 是否高亮,默认高亮,传入false禁用
 * @param isExpand 是否展开,默认合拢,传入true展开
 * @returns
 */
function fuzzySearch(searchField, isHighLight, isExpand){
    var zTreeObj = zTree;
    var nameKey = zTreeObj.setting.data.key.name; //获取name属性的key
    isHighLight = isHighLight===false?false:true;//除直接输入false的情况外,都默认为高亮
    isExpand = isExpand?true:false;
    zTreeObj.setting.view.nameIsHTML = isHighLight;//允许在节点名称中使用html,用于处理高亮

    var metaChar = '[\\[\\]\\\\\^\\$\\.\\|\\?\\*\\+\\(\\)]'; //js正则表达式元字符集
    var rexMeta = new RegExp(metaChar, 'gi');//匹配元字符的正则表达式

    // 过滤ztree显示数据
    function ztreeFilter(zTreeObj,_keywords,callBackFunc) {
        if(!_keywords){
            _keywords =''; //如果为空，赋值空字符串
        }

        // 查找符合条件的叶子节点
        function filterFunc(node) {
            if(node && node.oldname && node.oldname.length>0){
                node[nameKey] = node.oldname; //如果存在原始名称则恢复原始名称
            }
            //node.highlight = false; //取消高亮
            zTreeObj.updateNode(node); //更新节点让之前对节点所做的修改生效
            if (_keywords.length == 0) {
                //如果关键字为空,返回true,表示每个节点都显示
                zTreeObj.showNode(node);
                zTreeObj.expandNode(node,isExpand); //关键字为空时是否展开节点
                return true;
            }
            //节点名称和关键字都用toLowerCase()做小写处理
            if (node[nameKey] && node[nameKey].toLowerCase().indexOf(_keywords.toLowerCase())!=-1) {
                if(isHighLight){ //如果高亮，对文字进行高亮处理
                    //创建一个新变量newKeywords,不影响_keywords在下一个节点使用
                    //对_keywords中的元字符进行处理,否则无法在replace中使用RegExp
                    var newKeywords = _keywords.replace(rexMeta,function(matchStr){
                        //对元字符做转义处理
                        return '\\' + matchStr;

                    });
                    node.oldname = node[nameKey]; //缓存原有名称用于恢复
                    //为处理过元字符的_keywords创建正则表达式,全局且不分大小写
                    var rexGlobal = new RegExp(newKeywords, 'gi');//'g'代表全局匹配,'i'代表不区分大小写
                    //无法直接使用replace(/substr/g,replacement)方法,所以使用RegExp
                    node[nameKey] = node.oldname.replace(rexGlobal, function(originalText){
                        //将所有匹配的子串加上高亮效果
                        var highLightText =
                            '<span style="color: whitesmoke;background-color: darkred;">'
                            + originalText
                            +'</span>';
                        return  highLightText;
                    });
                    //================================================//
                    //node.highlight用于高亮整个节点
                    //配合setHighlight方法和setting中view属性的fontCss
                    //因为有了关键字高亮处理,所以不再进行相关设置
                    //node.highlight = true;
                    //================================================//
                    zTreeObj.updateNode(node); //update让更名和高亮生效
                }
                zTreeObj.showNode(node);//显示符合条件的节点
                return true; //带有关键字的节点不隐藏
            }

            zTreeObj.hideNode(node); // 隐藏不符合要求的节点
            return false; //不符合返回false
        }
        var nodesShow = zTreeObj.getNodesByFilter(filterFunc); //获取匹配关键字的节点
        processShowNodes(nodesShow, _keywords);//对获取的节点进行二次处理
    }

    /**
     * 对符合条件的节点做二次处理
     */
    function processShowNodes(nodesShow,_keywords){
        if(nodesShow && nodesShow.length>0){
            //关键字不为空时对关键字节点的祖先节点进行二次处理
            if(_keywords.length>0){
                $.each(nodesShow, function(n,obj){
                    var pathOfOne = obj.getPath();//向上追溯,获取节点的所有祖先节点(包括自己)
                    if(pathOfOne && pathOfOne.length>0){ //对path中的每个节点进行操作
                        // i < pathOfOne.length-1, 对节点本身不再操作
                        for(var i=0;i<pathOfOne.length-1;i++){
                            zTreeObj.showNode(pathOfOne[i]); //显示节点
                            zTreeObj.expandNode(pathOfOne[i],true); //展开节点
                        }
                    }
                });
            }else{ //关键字为空则显示所有节点, 此时展开根节点
                var rootNodes = zTreeObj.getNodesByParam('level','0');//获得所有根节点
                $.each(rootNodes,function(n,obj){
                    zTreeObj.expandNode(obj,true); //展开所有根节点
                });
            }
        }
    }

    //监听关键字input输入框文字变化事件
    $(searchField).bind('input propertychange', function() {
        var _keywords = $(this).val();
        searchNodeLazy(_keywords); //调用延时处理
    });

    var timeoutId = null;
    // 有输入后定时执行一次，如果上次的输入还没有被执行，那么就取消上一次的执行
    function searchNodeLazy(_keywords) {
        if (timeoutId) { //如果不为空,结束任务
            clearTimeout(timeoutId);
        }
        timeoutId = setTimeout(function() {
            ztreeFilter(zTreeObj,_keywords);    //延时执行筛选方法
            $(searchField).focus();//输入框重新获取焦点
        }, 500);
    }
}
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};